//
//  CancelAccountViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/11/3.
//

import UIKit
import YYKit
import WebKit

class CancelAccountViewController: BaseViewController {
    var phoneStr = ""
    var webView : WKWebView!
    var bodyColorHex: String = "#F2F7FA"
    var localHtmlStr: String = ""
    var scribWebViewHeight: CGFloat = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = Theme.F5Color
        let config = WKWebViewConfiguration.init()
        let userContentController = WKUserContentController()
        config.userContentController = userContentController
        
        self.webView = WKWebView.init(frame: CGRect(x: 14, y: NavBarHight, width: kScreenWidth - 28, height: kScreenHeight - NavBarHight - TabbarHeight - 50))
        self.webView.isHidden = true
        self.webView.uiDelegate = self
        self.webView.navigationDelegate = self
        self.webView.autoresizesSubviews = true
        self.webView.allowsBackForwardNavigationGestures = false
        self.webView.scrollView.showsVerticalScrollIndicator = false
        self.webView.scrollView.showsHorizontalScrollIndicator = false
        self.webView.isUserInteractionEnabled = true
        self.webView.scrollView.isUserInteractionEnabled = true
        self.webView.sizeToFit()
        self.view.addSubview(self.webView)
        self.webView.scrollView.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.new, context: nil)
        self.webView.layer.cornerRadius = 8
        self.webView.layer.masksToBounds = true
        
        self.webView.snp.makeConstraints { make in
            make.top.equalTo(NavBarHight + 10)
            make.left.equalTo(14)
            make.right.equalTo(-14)
            make.height.greaterThanOrEqualTo(200)
        }
        self.createBottomView()
        self.fetchGetNotice()
    }
    
    ///监听webview的高度
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        var tempSize = (change! as NSDictionary)["new"] as! CGSize
        if tempSize.height < 200 {
            tempSize.height = 200
        }
        self.webView.snp.updateConstraints { make in
            make.height.greaterThanOrEqualTo(tempSize)
        }
    }
    
    private func createBottomView(){
        let tempHeight: CGFloat = IphoneXMarginBottom + 54
        let bgView = UIView(frame: CGRect(x: 0, y: kScreenHeight - tempHeight, width: kScreenWidth, height: tempHeight))
        bgView.backgroundColor = .clear
        self.view.addSubview(bgView)
        
        let nextStepBtn = UIButton(frame: CGRect(x: 14, y: 4, width: kScreenWidth - 28, height: 46))
        nextStepBtn.backgroundColor = Theme.mainColor
        nextStepBtn.layer.cornerRadius = 8
        nextStepBtn.layer.masksToBounds = true
        nextStepBtn.setTitleColor(.white, for: .normal)
        nextStepBtn.setTitle(MMLocalizedString("next", comment: "下一步"), for: .normal)
        nextStepBtn.titleLabel?.font = UIFont(name: Theme.PingFangSCMedium, size: 16)
        nextStepBtn.addTarget(self, action: #selector(nextStepBtnAntion), for: .touchUpInside)
        bgView.addSubview(nextStepBtn)
        
        let yyLabel = YYLabel.init(frame: CGRect.init(x: 14, y: bgView.top - 40, width: kScreenWidth - 28, height: 40))
        yyLabel.numberOfLines = 0
        yyLabel.textColor = Theme.titleLabColor
        yyLabel.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        let privacy = MMLocalizedString("account_cancellation_agreement", comment: "《注销账号协议》")
        let str = MMLocalizedString("by_click_nextread_agree", comment: "点击下一步即代表您已经阅读并同意") + privacy
        let privacyLoc = str.findSubStringLocation(subString: privacy)
        let attStr = NSMutableAttributedString.init(string: str)
        attStr.lineSpacing = 8
        if privacyLoc > 0 {
            attStr.setTextHighlight(NSRange.init(location: privacyLoc, length: privacy.count), color: Theme.mainColor, backgroundColor: UIColor.clear, tapAction: {[weak self]  (containerView, attr, tRange, rect) in
                self?.fetchGetProtocol()
            })
        }
        yyLabel.attributedText = attStr
        self.view.addSubview(yyLabel)
    }
    
    ///注销账号提示
    private func fetchGetNotice(){
        self.view.showLoadingHUDText(MMLocalizedString("loadding", comment: "加载中"))
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.logoutAccountNote, objectType: ResignResModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as! ResignResModel
            if resultObj.code == "1" {
                self.loadHtmlData(title: resultObj.data?.title ?? "", msg: resultObj.data?.content ?? "")
                self.webView.isHidden = false
            }else{
                self.view.makeToast(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.view.handleLoading()
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    private func loadHtmlData(title: String, msg: String){
        let formatWeb = """
                <!DOCTYPEhtml>
                    <html>
                    <head>
                        <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"name="viewport">
                        <meta http-equiv="Content-Type"content="text/html; charset=UTF-8">
                    </head>
                    <style type="text/css">
                        img{
                            display:inline-block;
                            max-width:100%@;
                        }
                    </style>
                    <body style="background-color: white;">
                        <p style="font-size:26px; font-weight:500; height: 50px; text-align:center">%@</p>
                        <div>%@</div>
                    </body>
                    </html>
                """
        let tempStr = String(format: formatWeb,
                             "%",
                             title,
                             msg)
        self.webView.loadHTMLString(tempStr, baseURL: nil)
    }
    
    ///下一步
    @objc func nextStepBtnAntion(){
        self.getSMSCode()
    }
    
    ///注销账号协议
    private func fetchGetProtocol(){
        self.view.showLoadingHUDText(MMLocalizedString("loadding", comment: "加载中"))
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.logoutAccountAgreement, objectType: ResignResModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as! ResignResModel
            if resultObj.code == "1" {
                let vc = WebViewController()
                vc.titleStr = resultObj.data?.title ?? ""
                vc.localHtmlStr = resultObj.data?.content ?? ""
                self.navigationController?.pushViewController(vc, animated: true)
            }else{
                self.view.makeToast(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.view.handleLoading()
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    ///step1 注销获取验证码
    private func getSMSCode(){
        let areaCode = XTManageCenter.getLocalStringDataValue(aKey: UtilCenter.phoneCodeKey)
        let param: [String: String] = ["mobileAreaCode": areaCode,
                                       "phone": self.phoneStr,
                                       "sendType": "3"]
        self.view.showLoadingHUDText()
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.captchaGetCode(param: param), objectType: SMSCodeModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as? SMSCodeModel
            guard let code = resultObj?.code, code == "1" else {
                self.view.makeToast(message: resultObj?.msg ?? "")
                return
            }
//            XTAlertView.showAlertView(title: "当前验证码", message: resultObj?.data ?? "", cancelButtonTitle: "确定") { alertView, buttonIndex in
//                self.jumpToVerify()
//            }
            self.jumpToVerify()
        } error: { err in
            self.view.handleLoading()
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    ///step2 验证确认注销跳转
    private func jumpToVerify(){
        let vc = InputVerifyViewController()
        vc.pageType = .closeAccount
        vc.phoneStr = self.phoneStr
        self.navigationController?.pushViewController(vc, animated: true)
    }
}


extension CancelAccountViewController: WKNavigationDelegate{
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        printLog("开始加载")
    }
    
    func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!){
    }
    
}
